package com.marion.study.controller;

import com.marion.hellospringbootautoconfiguration.service.HelloService;
import com.marion.study.component.GoodsComponent;
import com.marion.study.config.AppConfig;
import com.marion.study.config.DataBaseConfig;
import com.marion.study.entity.UserEntity;
import com.marion.study.model.User;
import com.marion.study.repo.UserRepo;
import com.marion.study.service.AuthService;
import org.aspectj.lang.annotation.RequiredTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/")
public class IndexController {

    @Value(value = "${server.port}")
    private int port;

//    @Autowired
    private UserRepo userRepo;

    @Autowired
    private HelloService helloService;

    @GetMapping("/index")
    public Object index() {
        //1. 打印自定义配置
        HashMap<Object, Object> ret = new HashMap<>(16);
        ret.put("port", port);

        //2. 获得配置类信息
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        User user = (User) ctx.getBean("user");
        ret.put("user", user);
        System.out.println("user={}" + user.toString());

        AnnotationConfigApplicationContext urCtx = new AnnotationConfigApplicationContext(DataBaseConfig.class);
        User ur = (User) urCtx.getBean("ur");
        ret.put("ur", ur);
        System.out.println("ur={}" + ur.toString());

        //3. 通过Component获得Bean
        AnnotationConfigApplicationContext ctx1 = new AnnotationConfigApplicationContext(GoodsComponent.class);
        GoodsComponent goodsComponent = (GoodsComponent) ctx1.getBean("goodsComponent");
        ret.put("goodsId", goodsComponent.getGoodsId());

        //4. 通过JPA查询数据
        List<UserEntity> users = userRepo.findAll();
        ret.put("users", users);

        //5. 配置阿里云druid数据源
        AnnotationConfigApplicationContext ctx2 = new AnnotationConfigApplicationContext(DataBaseConfig.class);
        DataSource dataSource = (DataSource) ctx2.getBean("druidDb");
        System.out.println("dataSource={}" + dataSource.getClass());
        ret.put("druidDb", dataSource.getClass());

        //6. 获得自定义starter
        String name = helloService.sayHello("自定义");
        ret.put("name", name);

        return ret;
    }

}
